package controller;

import entity.*;
import service.*;
import util.UserSessionManager;
import view.UserView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class BlogController {
    private final UserService userService = new UserService();
    private final BlogService blogService = new BlogService();
    private final CommentService commentService = new CommentService();
    private final ReportService reportService = new ReportService();
    private final ColumnService columnService = new ColumnService();
    private final Scanner scanner = new Scanner(System.in);

    // 用于保存每篇文章的排序状态
    private final Map<Integer, String> blogSortOrderMap = new HashMap<>();
    private UserView userView;

    public void setUserView(UserView userView) {
        this.userView = userView;
    }

    // 默认排序按点赞数降序
    private String getSortOrderForBlog(int blogId) {
        return blogSortOrderMap.getOrDefault(blogId, "likeCount");
    }

    private final Map<Integer, String> columnSortOrderMap = new HashMap<>();

    private String getSortOrderForColumn(int columnId) {
        return columnSortOrderMap.getOrDefault(columnId, "createdTime");
    }

    public void showHotBlogs(String orderBy) {
        List<Blog> blogs = blogService.getHotBlogs(orderBy);
        showBlogs(blogs);
        Blog blog = operateBlog(blogs);
        if(blog == null) return;
        showBlogDetails(blog);
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        userView.showOptions(userId, blog.getId(), blog.getAuthorId());
    }

    public void showBlogs(List<Blog> blogs) {
        if (blogs.isEmpty()) return;
        int index = 1;  // 文章编号
        for (Blog blog : blogs) {
            System.out.println(index + ". " + blog.getTitle());
            index++;
        }
    }

    public Blog operateBlog(List<Blog> blogs) {
        while (true) {
            if (blogs.isEmpty()) {
                System.out.println("没有博文！");
                return null;
            }

            System.out.println("请输入想操作的文章编号(输入0退出): ");
            int blogIndex = scanner.nextInt();
            scanner.nextLine(); // 清空换行符

            if (blogIndex == 0) {
                System.out.println("退出");
                return null;
            }

            if (blogIndex > 0 && blogIndex <= blogs.size()) {
                return blogs.get(blogIndex - 1);
            } else {
                System.out.println("无效的编号，请重新输入！");
            }
        }
    }

    public void showBlogDetails(Blog blog) {
        blogService.incrementViewCount(blog.getId());

        System.out.println("文章标题: " + blog.getTitle());
        System.out.println("博主: " + userService.getUserById(blog.getAuthorId()).getUserName());
        System.out.println("内容: " + blog.getContent());
        System.out.println("点赞量: " + blog.getLikeCount());
        System.out.println("评论数: " + blog.getCommentCount());
        System.out.println("浏览量: " + blog.getViewCount());

        System.out.println("--------------------------------");

        // 获取当前文章的评论排序方式
        String sortOrder = getSortOrderForBlog(blog.getId());

        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        List<Comment> comments = commentService.getCommentsByBlogId(blog.getId(), sortOrder);
        if (comments.isEmpty()) {
            System.out.println("评论区：");
            System.out.println("暂无评论");
        } else {
            System.out.println("评论区（按 " + (sortOrder.equals("likeCount") ? "点赞数" : "发布时间") + " 排序）：");
            int commentIndex = 1;
            for (Comment comment : comments) {
                System.out.print(commentIndex +
                        ". 评论者: " + userService.getUserById(comment.getUserId()).getUserName() +
                        " 内容: " + comment.getContent() +
                        " 点赞数: " + comment.getLikeCount());
                if (commentService.isUserLikeComment(userId, comment.getId())) {
                    System.out.println("（已点赞）");
                }else{System.out.print("\n");}
                commentIndex++;
            }
        }
        System.out.println("--------------------------------");

    }

    public Comment operateComment(List<Comment> comments) {
        while (true) {
            if (comments.isEmpty()) {
                System.out.println("暂无评论！");
                return null;
            }

            System.out.println("请输入想操作的评论编号(输入0退出): ");
            int commentIndex = scanner.nextInt();
            scanner.nextLine(); // 清空换行符

            if (commentIndex == 0) {
                System.out.println("退出");
                return null;
            }

            if (commentIndex > 0 && commentIndex <= comments.size()) {
                return comments.get(commentIndex - 1);
            } else {
                System.out.println("无效的编号，请重新输入！");
            }
        }
    }

    public boolean isUserLikedBlog(int userId, int blogId) {
        return blogService.isUserLikedBlog(userId, blogId);
    }

    public void toggleLikeBlog(int userId, int blogId) {
        if (blogService.toggleLikeBlog(userId, blogId)) {
            System.out.println("取消点赞成功");
        } else {
            System.out.println("点赞成功");
        }
    }

    public void toggleComment(int userId, int blogId) {
        String sortOrder = getSortOrderForBlog(blogId);
        List<Comment> comments = commentService.getCommentsByBlogId(blogId, sortOrder);
        Comment comment = operateComment(comments);
        if (comment == null) return;

        if (commentService.toggleLikedComment(userId, comment.getId())) {
            System.out.println("取消点赞成功");
        } else {
            System.out.println("点赞成功");
        }
    }

    public boolean isFollowing(int userId, int authorId) {
        return userService.isFollowing(userId, authorId);
    }

    public void toggleFollowAuthor(int userId, int authorId) {
        if (authorId == userId) {
            System.out.println("不能关注自己！");
            return;
        }
        if (userService.toggleFollowAuthor(userId, authorId)) {
            System.out.println("取消关注成功");
        } else {
            System.out.println("关注成功");
        }
    }

    public void commentOnBlog(int blogId, int userId) {
        User user = userService.getUserById(userId);
        if (user.isBanned()) {
            System.out.println("您的账号已被封禁，无法发表评论！");
            return;
        }
        System.out.println("请输入评论内容：");
        String content = scanner.nextLine();
        commentService.addComment(blogId, userId, content);
        System.out.println("评论发布成功!");
    }

    public void deleteComment(int blogId) {
        String sortOrder = getSortOrderForBlog(blogId);
        List<Comment> comments = commentService.getCommentsByBlogId(blogId, sortOrder);
        Comment comment = operateComment(comments);
        if(comment == null) return;

        int userId = UserSessionManager.getInstance().getCurrentUser().getId();

        if (comment.getUserId() == userId || getBlogById(blogId).getAuthorId() == userId || userService.getUserById(userId).getRole().equals("admin")) {
            commentService.deleteComment(comment.getId(), blogId);
            System.out.println("评论删除成功！");
        } else {
            System.out.println("无法删除她人评论！");
        }
    }

    public void sortComments(int blogId) {
        String currentSortOrder = getSortOrderForBlog(blogId);
        String newSortOrder = currentSortOrder.equals("likeCount") ? "createdTime" : "likeCount";
        blogSortOrderMap.put(blogId, newSortOrder);
        System.out.println("已切换评论排序方式！");
    }

    public Blog getBlogById(int blogId) {
        return blogService.getBlogById(blogId);
    }

    public void reportBlog(int blogId) {
        System.out.println("请输入举报原因：");
        String reason = scanner.nextLine();

        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        reportService.reportBlog(blogId, userId, reason);

        System.out.println("确认举报该博文吗（yes/no)");
        String action = scanner.nextLine();

        if (action.equals("yes")) {
            System.out.println("举报成功！请等待管理员处理");
        } else {
            System.out.println("取消举报");
        }
    }

    public void searchBlogsByKeyword(String keyword) {
        List<Blog> blogs = blogService.searchBlogsByKeyword(keyword);
        showBlogs(blogs);
        Blog blog = operateBlog(blogs);
        if(blog == null) return;
        showBlogDetails(blog);
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        userView.showOptions(userId, blog.getId(), blog.getAuthorId());
    }

    public void showAuthors(List<User> authors) {
        if (authors.isEmpty()) return;
        int index = 1;
        for (User author : authors) {
            System.out.println(index + ". " + author.getUserName());
            index++;
        }
    }

    public User operateAuthor(List<User> authors) {
        while (true) {
            if (authors.isEmpty()) {
                System.out.println("没有博主！");
                return null;
            }

            System.out.println("请输入想操作的博主编号(输入0退出): ");
            int authorIndex = scanner.nextInt();
            scanner.nextLine();

            if (authorIndex == 0) {
                System.out.println("退出");
                return null;
            }

            if (authorIndex > 0 && authorIndex <= authors.size()) {
                return authors.get(authorIndex - 1);
            } else {
                System.out.println("无效的编号,请重新输入！");
            }
        }
    }

    public void searchAuthorsByKeyword(String keyword) {
        List<User> authors = userService.searchUsersByKeyword(keyword);
        showAuthors(authors);
        User author = operateAuthor(authors);
        if (author == null) return;
        List<Blog> blogs = blogService.getBlogsByAuthorId(author.getId());
        showBlogs(blogs);
        Blog blog = operateBlog(blogs);
        if(blog == null) return;
        showBlogDetails(blog);
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        userView.showOptions(userId, blog.getId(), blog.getAuthorId());
    }

    public void showColumns(List<Column> columns) {
        if (columns.isEmpty()) return;

        int index = 1;
        for (Column column : columns) {
            System.out.println(index + "、 " + column.getName());
            String orderBy = getSortOrderForColumn(column.getId());
            List<Blog> blogs = blogService.getBlogsByColumnId(column.getId(), orderBy);

            if (blogs.isEmpty()) {
                System.out.println("该专栏暂无博文！");
                return;
            }
            showBlogs(blogs);

            index++;
        }
    }

    public Column operateColumn(List<Column> columns) {
        while (true) {
            if (columns.isEmpty()) {
                System.out.println("没有专栏！");
                return null;
            }

            System.out.println("请输入想操作的专栏编号(输入0退出): ");
            int columnIndex = scanner.nextInt();
            scanner.nextLine(); // 清空换行符

            if (columnIndex == 0) {
                System.out.println("退出");
                return null;
            }

            if (columnIndex > 0 && columnIndex <= columns.size()) {
                return columns.get(columnIndex - 1);
            } else {
                System.out.println("无效的编号,请重新输入！");
            }
        }
    }

    public void searchColumnsByKeyword(String keyword) {
        List<Column> columns = columnService.searchColumnsByKeyword(keyword);
        showColumns(columns);
        Column column = operateColumn(columns);
        if (column == null) return;
        String orderBy = getSortOrderForColumn(column.getId());
        Blog blog = operateBlog(blogService.getBlogsByColumnId(column.getId(), orderBy));
        if(blog == null) return;
        showBlogDetails(blog);
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        userView.showOptions(userId, blog.getId(), blog.getAuthorId());
    }

    public void showMyBlogs() {
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        List<Blog> blogs = blogService.getBlogsByAuthorId(userId);
        if (blogs.isEmpty()) {
            System.out.println("暂无博文");
        }
        showBlogs(blogs);
        System.out.println("-----------------------------------------");
    }

    public void createBlog() {
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        User user = userService.getUserById(userId);  // 获取用户信息
        if (user.isBanned()) {
            System.out.println("您的账号已被封禁，无法发布文章！");
            return;
        }

        System.out.print("请输入标题: ");
        String title = scanner.nextLine();
        System.out.print("请输入内容: ");
        String content = scanner.nextLine();

        if (title.isEmpty() || content.isEmpty()) {
            System.out.println("标题或内容不能为空，博文发布失败！！");
            return;
        }
        blogService.createBlog(title, content, userId);
        System.out.println("博文发布成功！");
    }

    public void updateBlog() {
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        List<Blog> blogs = blogService.getBlogsByAuthorId(userId);

        if (blogs.isEmpty()) {
            System.out.println("您还没有发布任何博文！");
            return;
        }

        Blog blog = operateBlog(blogs);

        System.out.print("标题（可回车跳过）: ");
        String title = scanner.nextLine();
        System.out.print("新内容（可回车跳过）: ");
        String content = scanner.nextLine();

        if (title.isEmpty()) title = blog.getTitle();
        if (content.isEmpty()) content = blog.getContent();

        blogService.updateBlog(title, content, userId);
        System.out.println("修改成功！");
    }

    public void deleteBlog() {
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        List<Blog> blogs = blogService.getBlogsByAuthorId(userId);

        if (blogs.isEmpty()) {
            System.out.println("您还没有发布任何博文！");
            return;
        }

        Blog blog = operateBlog(blogs);
        if (blog == null) return;
        blogService.deleteBlog(blog.getId());
        System.out.println("删除成功！");
    }

    public void showMyBlogDetails() {
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        List<Blog> blogs = blogService.getBlogsByAuthorId(userId);
        if (blogs.isEmpty()) {
            System.out.println("您还没有发布任何博文！");
            return;
        }
        Blog blog = operateBlog(blogs);
        if(blog == null) return;
        showBlogDetails(blog);
    }

    public void deleteCommentOnMyBlog() {
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        List<Blog> blogs = blogService.getBlogsByAuthorId(userId);
        if (blogs.isEmpty()) {
            System.out.println("您还没有发布任何博文！");
            return;
        }

        Blog blog = operateBlog(blogs);
        if (blog == null) return;
        showBlogDetails(blog);

        deleteComment(blog.getId());
    }

    public void showMyColumns() {
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        List<Column> columns = columnService.getColumnsByUserId(userId);
        if(columns.isEmpty()) System.out.println("暂无专栏");
        showColumns(columns);
        System.out.println("---------------------------------");

        List<Blog> blogs = blogService.getBlogsWithoutColumn(userId);
        System.out.println("未添加进入专栏的文章: ");
        if(blogs.isEmpty()) {
            System.out.println("暂无博文");
        }else{
            showBlogs(blogs);
        }
        System.out.println("---------------------------------");
    }

    public void createColumn() {
        System.out.println("请输入专栏名字: ");
        String name = scanner.nextLine();

        if (name.isEmpty()) {
            System.out.println("名字不能为空！");
            return;
        }
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        columnService.createColumn(name, userId);
        System.out.println("创建成功！");
    }

    public void addBlogToMyColumn() {
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        List<Blog> blogs = blogService.getBlogsWithoutColumn(userId);
        Blog blog = operateBlog(blogs);
        if (blog == null) return;
        if (columnService.addBlogToColumn(blog.getId(), userId)) {
            System.out.println("添加成功！");
        }
    }

    public void deleteColumn() {
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        List<Column> columns = columnService.getColumnsByUserId(userId);
        Column column = operateColumn(columns);
        if (column == null) return;
        if (columnService.deleteColumn(column.getId())) System.out.println("删除成功！");
    }

    public void removeMyBlog() {
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        List<Column> columns = columnService.getColumnsByUserId(userId);
        Column column = operateColumn(columns);
        if (column == null) return;
        String orderBy = getSortOrderForColumn(column.getId());
        Blog blog = operateBlog(blogService.getBlogsByColumnId(column.getId(), orderBy));
        if (columnService.removeBlogFromColumn(blog.getId())) {
            System.out.println("移除成功！");
        }
    }

    public void getFolloweeUsers() {
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        List<User> followeeUsers = userService.getFolloweeUsers(userId);
        showAuthors(followeeUsers);
        if (followeeUsers.isEmpty()) {
            System.out.println("暂无关注的博主");
            return;
        }
        User followee = operateAuthor(followeeUsers);
        if(followee == null) return;
        toggleFollowAuthor(userId, followee.getId());
    }

    public void toggleTopStatus() {
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        List<Column> columns = columnService.getColumnsByUserId(userId);
        Column column = operateColumn(columns);
        if (column == null) return;
        String orderBy = getSortOrderForColumn(column.getId());
        Blog blog = operateBlog(blogService.getBlogsByColumnId(column.getId(), orderBy));
        if (blog == null) return;
        boolean newStatus = !blog.isTop();  // 反转置顶状态
        if (blogService.toggleTopStatus(blog.getId(), newStatus)) {
            System.out.println(newStatus ? "置顶成功！" : "取消置顶成功！");
        } else {
            System.out.println("操作失败！");
        }
    }

    public void showLikedBlogs() {
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        List<Blog> blogs = blogService.getLikedBlogsByUserId(userId);
        if (blogs.isEmpty()) {
            System.out.println("暂无博文");
            return;
        }
        showBlogs(blogs);
    }

    public void toggleColumnBlogSortOrder() {
        int userId = UserSessionManager.getInstance().getCurrentUser().getId();
        List<Column> columns = columnService.getColumnsByUserId(userId);
        Column column = operateColumn(columns);
        if (column == null) return;

        String currentSortOrder = getSortOrderForColumn(column.getId());
        String newSortOrder = currentSortOrder.equals("createdTime") ? "updatedTime" : "createdTime";
        columnSortOrderMap.put(column.getId(), newSortOrder);
        System.out.println("排序方式已切换为：" + (newSortOrder.equals("createdTime") ? "创建时间" : "更新时间"));
    }

    public void banUsers(int userId) {
        User user = userService.getUserById(userId);
        if(user.isBanned()){
            reportService.unbanUser(userId);
            System.out.println("解禁成功");
        }else {
            reportService.banUser(userId);
            System.out.println("封禁成功");
        }
    }

    public void deleteBlog(int blogId) {
        blogService.deleteBlog(blogId);
        System.out.println("删除成功！");
    }

    public void showReports() {
        Map<Integer, Integer> blogReportCounts = reportService.getBlogReportCounts();

        if (blogReportCounts.isEmpty()) {
            System.out.println("暂无未审核的举报记录！");
        } else {
            for (Map.Entry<Integer, Integer> entry : blogReportCounts.entrySet()) {
                int blogId = entry.getKey();
                int reportCount = entry.getValue();
                System.out.println("文章 ID: " + blogId + " 作者 ID: " + getBlogById(blogId).getAuthorId() + "  被举报次数: " + reportCount);
            }
        }
    }

    public void updateReport(int blogId) {
        Map<Integer, Integer> blogReportCounts = reportService.getBlogReportCounts();

        for (Map.Entry<Integer, Integer> entry : blogReportCounts.entrySet()) {
            if (entry.getKey() == blogId) {
                List<Report> reports = reportService.getUnreviewedReports();
                for (Report report : reports) {
                    if (report.getBlogId() == blogId && report.getStatus().equals("PENDING")) {
                        reportService.auditReport(report.getId());
                        System.out.println("举报已通过审核，状态已更新为 'RESOLVED'");
                    }
                }
            }
        }
    }
}